﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using System.Web.Script.Serialization;
using System.Web;
using System.IO;
using System.Text;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Net;
using System.Configuration;
using System.Diagnostics;
using System.Data.Odbc;
using System.Data;
using System.Data.OleDb;

namespace Common
{
    public class Commons
    {
        public static string[] path = HttpContext.Current.Request.Url.AbsoluteUri.Split('/');
        //public static string domain = "http://192.168.31.49:8080";// path[0]+"//"+path[1]+path[2];
        public static string domain = "https://shop.qiyedaishu.com";
        //public static string domain = "http://192.168.1.111";// path[0]+"//"+path[1]+path[2];
        public static int PageSize = 20;
        public static Dictionary<int, string> OrderState = new Dictionary<int, string>(); //订单状态
        public static Dictionary<int, string> Position = new Dictionary<int, string>(); //广告位
        public static Dictionary<int, string> ActivePosition = new Dictionary<int, string>(); //活动位置
        public static Dictionary<string, string> PostCom = new Dictionary<string, string>(); //物流公司
        public static Dictionary<int, string> PostState = new Dictionary<int, string>(); //物流状态
        public static Dictionary<int, string> Sex = new Dictionary<int, string>(); //性别
        public static Dictionary<int, string> Grade = new Dictionary<int, string>(); //会员级别
        static Commons()
        {
            OrderState.Add(0, "待付款");
            OrderState.Add(1, "待发货");
            OrderState.Add(2, "待收货");
            OrderState.Add(3, "待评价");
            OrderState.Add(4, "已完成");
            OrderState.Add(5, "退货");

            Position.Add(0, "");
            Position.Add(1, "首页轮播图");
            Position.Add(2, "首页横幅广告");

            ActivePosition.Add(0, "");
            ActivePosition.Add(1, "左1");
            ActivePosition.Add(2, "右1");
            ActivePosition.Add(3, "右2");
            ActivePosition.Add(4, "右3");

            PostCom.Add("", "");
            PostCom.Add("顺丰快递", "SF");
            PostCom.Add("邮政EMS", "EMS");
            PostCom.Add("申通快递", "STO");
            PostCom.Add("中通快递", "ZTO");
            PostCom.Add("圆通快递", "YTO");
            PostCom.Add("德邦物流", "DBL");
            PostCom.Add("京东快递", "JD");

            PostState.Add(-1, "单号或快递公司代码错误");
            PostState.Add(0, "暂无轨迹");
            PostState.Add(2, "在途中");
            PostState.Add(3, "已签收");
            PostState.Add(4, "问题件");

            Sex.Add(0,"未知");
            Sex.Add(1, "男");
            Sex.Add(2, "女");

            Grade.Add(0, "未知");
            Grade.Add(1, "普通会员");
            Grade.Add(2, "白金会员");
            Grade.Add(3, "黄金会员");
            Grade.Add(4, "钻石会员");

        }
        public static string GetFaild(string msg)
        {
            dynamic dy = new ExpandoObject();
            dy.state = false;
            dy.msg = msg;
            return SerializeHelper.ToJsonByDynamic(dy);
        }
        public static string GetSuccess(string msg, object data)
        {
            dynamic dy = new ExpandoObject();
            dy.state = true;
            dy.msg = msg;
            dy.data = data;
            return SerializeHelper.ToJsonByDynamic(dy);
        }
        public static string GetSuccess(string msg, object data, int count)
        {
            dynamic dy = new ExpandoObject();
            dy.state = true;
            dy.code = 0;
            dy.count = count;
            dy.msg = msg;
            dy.data = data;
            dy.pagesize = Commons.PageSize;
            return SerializeHelper.ToJsonByDynamic(dy);
        }
        //获取config文件value
        public static string GetConfig(string key)
        {
            if (!string.IsNullOrEmpty(key) &&
                ConfigurationManager.AppSettings.AllKeys.Contains(key))
            {
                return ConfigurationManager.AppSettings[key].ToString();
            }
            return string.Empty;
        }
        /// <summary>
        /// 启动服务器应用程序
        /// </summary>
        public static void ReStartServer()
        {
            try
            {
                Process[] processes = Process.GetProcesses();
                foreach (Process p in processes)
                {
                    if (p.ProcessName == "House")
                    {
                        p.Kill();
                    }
                }
                System.Diagnostics.Process.Start("D:/www/houseserver/House.exe");
            }
            catch (Exception)
            {
            }
        }
        /// <summary>
        /// 过滤HTML
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string FilterHTML(string str)
        {
            str = Regex.Replace(str, @"<[\s\S]*?>", "");
            return str.Replace("&nbsp;", "");
        }
        /// <summary>
        /// URL字符编码
        /// </summary>
        public static string UrlEncode(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return "";
            }
            str = str.Replace("'", "");
            return HttpContext.Current.Server.UrlEncode(str);
        }

        /// <summary>
        /// URL字符解码
        /// </summary>
        public static string UrlDecode(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return "";
            }
            return HttpContext.Current.Server.UrlDecode(str);
        }
        /// <summary>
        /// 获取客户端IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetWebClientIP()
        {

            string userIP = "未获取用户IP";

            try
            {
                if (System.Web.HttpContext.Current == null
            || System.Web.HttpContext.Current.Request == null
            || System.Web.HttpContext.Current.Request.ServerVariables == null)
                    return "";

                string CustomerIP = "";

                //CDN加速后取到的IP simone 090805
                CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
                if (!string.IsNullOrEmpty(CustomerIP))
                {
                    return CustomerIP;
                }

                CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];


                if (!String.IsNullOrEmpty(CustomerIP))
                    return CustomerIP;

                if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                {
                    CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                    if (CustomerIP == null)
                        CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
                else
                {
                    CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                }

                if (string.Compare(CustomerIP, "unknown", true) == 0)
                    return System.Web.HttpContext.Current.Request.UserHostAddress;
                return CustomerIP;
            }
            catch { }

            return userIP;

        }
        /// <summary> 
        /// 取得客户端真实IP。如果有代理则取第一个非内网地址 
        /// </summary> 
        public static string IPAddress
        {
            get
            {
                string result = String.Empty;
                result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (result != null && result != String.Empty)
                {
                    //可能有代理 
                    if (result.IndexOf(".") == -1)     //没有“.”肯定是非IPv4格式 
                        result = null;
                    else
                    {
                        if (result.IndexOf(",") != -1)
                        {
                            //有“,”，估计多个代理。取第一个不是内网的IP。 
                            result = result.Replace(" ", "").Replace("'", "");
                            string[] temparyip = result.Split(",;".ToCharArray());
                            for (int i = 0; i < temparyip.Length; i++)
                            {
                                if (IsIPAddress(temparyip[i])
                                    && temparyip[i].Substring(0, 3) != "10."
                                    && temparyip[i].Substring(0, 7) != "192.168"
                                    && temparyip[i].Substring(0, 7) != "172.16.")
                                {
                                    return temparyip[i];     //找到不是内网的地址 
                                }
                            }
                        }
                        else if (IsIPAddress(result)) //代理即是IP格式 
                            return result;
                        else
                            result = null;     //代理中的内容 非IP，取IP 
                    }
                }
                string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];


                if (null == result || result == String.Empty)
                    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                if (result == null || result == String.Empty)
                    result = HttpContext.Current.Request.UserHostAddress;
                return result;
            }

        }
        /// <summary>
        /// 是否是IP地址格式
        /// </summary>
        /// <param name="str1"></param>
        /// <returns></returns>
        public static bool IsIPAddress(string str1)
        {
            if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;
            string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";
            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
            return regex.IsMatch(str1);
        }
        /// <summary>
        /// 获取星期
        /// </summary>
        /// <returns></returns>
        public static string GetWeek()
        {
            string[] Day = new string[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
            return Day[Convert.ToInt32(DateTime.Now.DayOfWeek.ToString("d"))].ToString();
        }
        /// <summary>
        /// 获取日期
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static string getMonthDay(DateTime date)
        {
            string year_day = "";
            if (date.Year == DateTime.Now.Year && date.Month == DateTime.Now.Month)
            {
                if (date.Day == DateTime.Now.Day)
                {
                    year_day = "今天 ";
                }
                else if (date.Day == (DateTime.Now.Day - 1))
                {
                    year_day = "昨天 ";
                }
                else if (date.Day == (DateTime.Now.Day - 2))
                {
                    year_day = "前天 ";
                }
                else if (date.Day == (DateTime.Now.Day + 1))
                {
                    year_day = "明天 ";
                }
                else if (date.Day == (DateTime.Now.Day + 2))
                {
                    year_day = "后天 ";
                }
                else
                {
                    year_day = date.Month + "月" + date.Day + "日 ";
                }
            }
            else
            {
                year_day = date.Month + "月" + date.Day + "日 ";
            }

            return year_day;
        }
        public static string getMonthDayHourMinute(DateTime date)
        {
            string year_day = "";
            string minite = date.Minute.ToString();
            if (date.Year == DateTime.Now.Year && date.Month == DateTime.Now.Month)
            {
                if (date.Day == DateTime.Now.Day)
                {
                    year_day = "今天 ";
                }
                else if (date.Day == (DateTime.Now.Day - 1))
                {
                    year_day = "昨天 ";
                }
                else if (date.Day == (DateTime.Now.Day - 2))
                {
                    year_day = "前天 ";
                }
                else if (date.Day == (DateTime.Now.Day + 1))
                {
                    year_day = "明天 ";
                }
                else if (date.Day == (DateTime.Now.Day + 2))
                {
                    year_day = "后天 ";
                }
                else
                {
                    year_day = date.Month + "月" + date.Day + "日 ";
                }
            }
            else
            {
                year_day = date.Month + "月" + date.Day + "日 ";
            }
            if (minite.Length < 2)
            {
                minite = "0" + minite;
            }
            return year_day + date.Hour + ":" + minite;
        }
        /// <summary>
        /// 计算两个日期的时间间隔,返回的是时间间隔的日期差的绝对值.
        /// </summary>
        /// <param name="DateTime1">第一个日期和时间</param>
        /// <param name="DateTime2">第二个日期和时间</param>
        /// <returns></returns>
        public static int DateDiff(DateTime DateTime1, DateTime DateTime2, string Flag)
        {
            double dateDiff = 0;
            try
            {
                TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
                TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
                TimeSpan ts = ts1.Subtract(ts2).Duration();
                if (Flag == "Y")
                {
                    dateDiff = ts.TotalDays / 365;
                }
                else if (Flag == "D")
                {
                    dateDiff = ts.TotalDays;
                }
                else if (Flag == "H")
                {
                    dateDiff = ts.TotalHours;
                }
                else if (Flag == "M")
                {
                    dateDiff = ts.TotalMinutes;
                }
                else if (Flag == "S")
                {
                    dateDiff = ts.TotalSeconds;
                }

            }
            catch
            {
            }
            return (int)dateDiff;
        }
        /// <summary>
        /// 读取Excel到DataTable
        /// </summary>
        /// <param name="pathName"></param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public static DataTable ExcelToDataTable(string pathName, string sheetName)
        {
            DataTable tbContainer = new DataTable();
            string strConn = string.Empty;
            if (string.IsNullOrEmpty(sheetName)) { sheetName = "Sheet1"; }
            FileInfo file = new FileInfo(pathName);
            if (!file.Exists) { throw new Exception("文件不存在"); }
            string extension = file.Extension;
            switch (extension)
            {
                case ".xls":
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
                    break;
                case ".xlsx":
                    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
                    break;
                default:
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
                    break;
            }
            //链接Excel
            OleDbConnection cnnxls = new OleDbConnection(strConn);
            //读取Excel里面有 表Sheet1
            OleDbDataAdapter oda = new OleDbDataAdapter(string.Format("select * from [{0}$]", sheetName), cnnxls);
            DataSet ds = new DataSet();
            //将Excel里面有表内容装载到内存表中！
            oda.Fill(tbContainer);
            return tbContainer;
        }

        /// <summary>
        /// 获取CSV导入的数据
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="fileName">文件名称(.csv不用加)</param>
        /// <returns></returns>
        public static DataTable CsvToDataTable(string filePath, string fileName)
        {
            string path = Path.Combine(filePath, fileName + ".csv");
            string connString = @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + filePath + ";Extensions=asc,csv,tab,txt;";
            try
            {
                using (OdbcConnection odbcConn = new OdbcConnection(connString))
                {
                    odbcConn.Open();
                    OdbcCommand oleComm = new OdbcCommand();
                    oleComm.Connection = odbcConn;
                    oleComm.CommandText = "select * from [" + fileName + "#csv]";
                    OdbcDataAdapter adapter = new OdbcDataAdapter(oleComm);
                    DataSet ds = new DataSet();
                    adapter.Fill(ds, fileName);
                    return ds.Tables[0];
                    odbcConn.Close();
                }
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
            }
            catch (Exception ex)
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                throw ex;
            }
        }
        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="str"></param>
        public static void Log(string str)
        {
            string path = HttpContext.Current.Server.MapPath("/log.txt");
            if (!System.IO.File.Exists(path))
            {
                System.IO.FileStream f = System.IO.File.Create(path);
                f.Close();
                f.Dispose();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(path, true, System.Text.Encoding.GetEncoding("utf-8"));//true为追加,false为覆盖
            System.Text.Encoding.GetEncoding("gb2312");
            f2.WriteLine("=======================" + DateTime.Now + "=======================");
            f2.WriteLine(str);
            f2.Close();
            f2.Dispose();
        }
        /// <summary>
        /// sign验证
        /// </summary>
        /// <returns></returns>
        public static bool CheckSign()
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                string action = JobRequest.GetRequestString("act");
                string sign = JobRequest.GetRequestString("sign");
                sb.AppendFormat("account={0}&act={1}&key={2}", "COMPANY_MOBILE_CLIENT", action, "345E6B86CF4E43A452G563078E5ADEFF");
                string signstr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sb.ToString(), "MD5").ToLower();
                return sign == signstr;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// 字符串截取
        /// </summary>
        /// <param name="str"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string SubString(string str, int len)
        {
            if (str.Length > len)
            {
                return str.Substring(0, len);
            }
            else
            {
                return str;
            }
        }

        /// <summary>
        /// 生成订单号
        /// </summary>
        /// <param name="head">前缀，比如:PO</param>
        /// <param name="num">单号</param>
        /// <returns></returns>
        public static string ToNum(string head, string num)
        {
            var newnum = "";
            var date = DateTime.Now.ToString("yyyyMMdd");
            if (num == "" || num == null)
            {
                newnum = head + date + "0001";
            }
            else
            {
                if (num.Length == 14)
                {
                    int maxnum = int.Parse(num.Substring(10, 4)) + 1;
                    if (maxnum.ToString().Length == 1)
                    {
                        newnum = newnum = head + date + "000" + maxnum;
                    }
                    else if (maxnum.ToString().Length == 2)
                    {
                        newnum = newnum = head + date + "00" + maxnum;
                    }
                    else if (maxnum.ToString().Length == 3)
                    {
                        newnum = newnum = head + date + "0" + maxnum;
                    }
                    else if (maxnum.ToString().Length == 4)
                    {
                        newnum = newnum = head + date + maxnum;
                    }
                    else { }
                }
            }
            return newnum;
        }


        /// <summary>
        /// 给字符串两边添加逗号
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string AddDou(string str)
        {
            return "," + str.Trim(',') + ",";
        }
        /// <summary>
        /// SQL关键词过滤
        /// </summary>
        /// <param name="InText"></param>
        /// <returns></returns>
        public static bool SqlFilter(string InText)
        {
            string word = "and|exec|insert|select|delete|update|chr|mid|master|or|truncate|char|declare|join";
            if (InText == null)
                return false;
            foreach (string i in word.Split('|'))
            {
                if ((InText.ToLower().IndexOf(i + " ") > -1) || (InText.ToLower().IndexOf(" " + i) > -1))
                {
                    return true;
                }
            }
            return false;
        }
        public static string GetImg(string path, int size)
        {
            string[] files = path.Split('.');
            string ext = "." + files[files.Length - 1];
            return path.Replace(ext, "") + "_" + size + ext;
        }

        public static string TranRN(string str)
        {
            return str.Replace("\r\n", "<br>").Replace("\r", "<br>").Replace("\n", "<br>").Replace(" ", "&nbsp;");
        }

        //字符编码转汉字
        public static string UnicodeToGB(string text)
        {
            System.Text.RegularExpressions.MatchCollection mc = System.Text.RegularExpressions.Regex.Matches(text, "\\\\u([\\w]{4})");
            if (mc != null && mc.Count > 0)
            {
                foreach (System.Text.RegularExpressions.Match m2 in mc)
                {
                    string v = m2.Value;
                    string word = v.Substring(2);
                    byte[] codes = new byte[2];
                    int code = Convert.ToInt32(word.Substring(0, 2), 16);
                    int code2 = Convert.ToInt32(word.Substring(2), 16);
                    codes[0] = (byte)code2;
                    codes[1] = (byte)code;
                    text = text.Replace(v, Encoding.Unicode.GetString(codes));
                }
            }
            else
            {

            }
            return text;
        }
        //ip地址转城市名
        public static string IpToAddress(string ip)
        {
            try
            {
                WeiXin wx = new WeiXin();
                string str = wx.HttpGet("http://ip.taobao.com/service/getIpInfo.php?ip=" + ip, "");
                string unicode = UnicodeToGB(str);
                dynamic json = wx.ConvertJson(unicode);
                return json.data.region + json.data.city;
            }
            catch (Exception ex) { }
            return "";
        }

        //解决头像路径参数里有小数点
        public static string GetHead(string path, int size)
        {
            int index = path.IndexOf('.');
            return path.Substring(0, index) + "_" + size + path.Substring(index, path.Length - index);
        }

        //获取Token
        public static string GetToken()
        {
            return Guid.NewGuid().ToString("N");
        }

        
    }
}
